import os
import subprocess
from multiprocessing import Pool
from Params import configs  # 导入配置


def run_batch_script_for_model(model_name):
    try:
        fmu_filename = model_name.replace('.', '_') + '.fmu'
        model_fmu_path = os.path.join(configs.fmu_res, fmu_filename)
        output_log_path = os.path.join(configs.output_log_path, f"{model_name}.txt")
        subprocess.run([
            "run_ms.bat",
            model_fmu_path,
            configs.extracted_fmu_path,
            configs.msbuild_path,
            configs.project_path,
            configs.build_exe_path,
            configs.upper_project_path,
            output_log_path
        ], check=True, shell=True)
        print(f"Successfully processed model {model_name}")
    except subprocess.CalledProcessError as e:
        print(f"Error processing model {model_name}: {e}")


def process_models():
    # 读取模型列表
    with open('models2.txt', 'r') as file:
        model_names = file.read().splitlines()

    if not os.path.exists(configs.output_log_path):
        os.mkdir(configs.output_log_path)

    model_names = [model_name for model_name in model_names if not os.path.exists(os.path.join(configs.fmu_res, model_name))]

    # with Pool(processes=os.cpu_count()) as pool:
    with Pool(processes=1) as pool:
        pool.map(run_batch_script_for_model, model_names)


if __name__ == '__main__':
    process_models()
